package com.zhl.erp;

import com.alibaba.excel.EasyExcel;

import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: demos
 * @description:
 * @author: 刘振华
 * @create: 2020-07-21 10:32
 **/
public class ExcelHandle {
	private Map<String,String> relationMap = new HashMap<>();
	/**
	* @Description:  将csv转为map
	* @Author: 刘振华
	* @Date: 2020/7/21 18:19
	*/
	public Map<String,String> getMap(String ae){
		BufferedReader br = null;
		Map<String,String> map = new HashMap<>();
		try {
			br = new BufferedReader(new FileReader(new File(ae)));
			br.lines().forEach(line->{
				String[] split = line.split(",");
				map.put(split[0],split[1]);
			});
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			if(br != null){
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return map;
	}
	public Map<String,String> getRelationMap(String path,String ae){
		a52ErpMap(path);
		File aeFile = new File(ae);
		if(aeFile.exists()){
			aeFile.delete();
		}
		BufferedWriter bw = null;
		try {
			aeFile.createNewFile();
			bw = new BufferedWriter(new FileWriter(aeFile));
			for(String key : relationMap.keySet()){
				String value = relationMap.get(key) == null ? "" : relationMap.get(key);
				bw.write(key+","+value);
				bw.newLine();
			}
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			if(bw != null){
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return relationMap;
	}
	/**
	* @Description: 循环将该路径下所有的xls文件处理
	 * a5:erp
	* @Author: 刘振华
	* @Date: 2020/7/21 10:36
	*/
	private void a52ErpMap(String path){
		File file = new File(path);
		if(file.isDirectory()){
			Arrays.asList(file.list()).forEach(tf-> a52ErpMap(path + File.separator + tf));
		}else if(file.getName().endsWith("xls")){
			//处理excel,写到一个csv中即可
			handle(file);
		}
	}

	private void handle(File file){
		System.out.println(file.getName());
		List<Object> objects = EasyExcel.read(file).headRowNumber(0).doReadAllSync();
		Map<Integer,Object> first = (Map)objects.get(0);
		Integer a5ID = getKey(first,"EVENTID");
		if(a5ID == null){
			throw new RuntimeException("没有EVENTID,"+file.getAbsolutePath()+"=="+file.getName());
		}
		//将剩余列的对应关系找出来，csv形式存储
		for(int i = 2; i < objects.size(); i++){
			Map<Integer,Object> tmap = (Map) objects.get(i);
			String a5Str = (tmap.get(a5ID) == null?"":tmap.get(a5ID)).toString().trim();
			if(a5Str.endsWith("ID")){
				continue;
			}
			String erpStr = (tmap.get(0) == null?"":tmap.get(0)).toString().trim();
			String s = relationMap.get(a5Str);
			if(s == null || s.trim().equals("")){
				relationMap.put(a5Str,erpStr);
			}
		}
	}

	//根据value找到key
	private Integer getKey(Map<Integer,Object> map,String value){
		for(Integer key:map.keySet()){
			if(value.equals(map.get(key).toString())){
				return key;
			}
		}
		return null;
	}

}
